package com.authine.cloudpivot.web.api.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.TaskReportFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.dao.AppFunctionMapper;
import com.authine.cloudpivot.web.api.domain.dto.LeJuanDataDTO;
import com.authine.cloudpivot.web.api.exception.PortalException;
import com.authine.cloudpivot.web.api.model.qc.TaskReportModel;
import com.authine.cloudpivot.web.api.service.GetLeJuanDataService;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "外企德科相关接口", tags = "乐卷同步接口")
@RestController
@RequestMapping("/api/GetLeJuanData")
@Slf4j
@Validated
@Component
public class GetLeJuanDataController extends BaseController {

    @Value("${lejuan.url}")
    private String url;

    @Autowired
    private GetLeJuanDataService getLeJuanDataService;
    @Autowired
    private AppFunctionMapper appFunctionMapper;

    @Reference(version = "1.00")
    private TaskReportFacade taskReportFacade;

    /**
     * @Description : 获取乐卷数据
     * @param ：
     * @author : Liun
     * @date : 2021/3/3
     */
    @GetMapping({"/getDataFromLejuan"})
    @ApiOperation(value = "获取乐卷数据",notes = "获取乐卷数据")
    @ResponseBody
    public ResponseResult<?> getDataFromLejuan(){
        ResponseResult responseResult = this.getDataPubblic();
        return responseResult;
    }


    /**
     * @Description : 乐卷同步接口
     * @param ：
     * @author : Liun
     * @date : 2021/3/16
     */
    public ResponseResult getDataPubblic(){
        JSONObject json = new JSONObject();
        Long statusReal = 200L;
        try {
            //获取项目QC任务名称
            String projects = taskReportFacade.getProjects();
            TaskReportModel taskReportModel = JSON.parseObject(projects, TaskReportModel.class);
            List<Map<String, String>> prjList = taskReportModel.getProjects();
            if(prjList.size()>0){
                String subjectName;
                String project_name;
                String QC_task_name;
                String prjName;
                String subjectPerson;
                Map<String, String> parameters = new HashMap<>();
                for(Map<String,String> map:prjList){
                    subjectName = map.get("subjectName");
                    project_name = map.get("project_name");
                    QC_task_name = map.get("djRound");
                    subjectPerson = map.get("subjectPerson");
                    String id = map.get("id");
                    String creater = map.get("creater");
                    prjName = project_name + QC_task_name;
                    parameters.put("prjName",prjName);
                    //获取乐卷数据
                    List<LeJuanDataDTO> leJuanDataList = getLeJuanDataService.getDataFromLejuan(url, parameters);
                    //新增
                    if(leJuanDataList.size() > 0){
                        //删除数据
                        getLeJuanDataService.deleteProjectTaskIssueExist(project_name,QC_task_name);
                        //获取门店集合
                        Map<String, Map<String, String>> storesMap = getLeJuanDataService.getStoresList(subjectName);
                        this.createProjectTaskIssue(leJuanDataList,creater,project_name,QC_task_name,id,storesMap,subjectName,subjectPerson);
                    }
                }
            }
            //计算下发
            taskReportFacade.getXiaFaDataLejuan();
        } catch (PortalException e) {
            statusReal = 500L;
            json.put("message", "获取数据失败：" + e.getErrMsg());
        }
        return ResponseResult.<JSONObject>builder().errcode(statusReal).data(json).build();
    }

    /**
     * @Description :生成項目任务下发数据
     * @param ： leJuanDataList
     * @param ： userId
     * @author : Liun
     * @date : 2021/3/5
     */
    public void createProjectTaskIssue(List<LeJuanDataDTO> leJuanDataList,String userId,String project_name,String QC_task_name,String id,Map<String, Map<String, String>> storesMap,String subjectName,String subjectPerson){
        BizObjectModel bizObjectModel;
        Map<String, Object> data;

        Object persons = appFunctionMapper.getPersons(id);
        for(LeJuanDataDTO leJuanDataDTO : leJuanDataList) {
            bizObjectModel = new BizObjectModel();
            bizObjectModel.setSchemaCode("ProjectTaskIssue");
            bizObjectModel.setFormCode("ProjectTaskIssue");
            bizObjectModel.setSequenceStatus("COMPLETED");
            data = bizObjectModel.getData();

            String taskCode = leJuanDataDTO.getTaskCode();
            Map<String, String> map = storesMap.get(taskCode);
            if(MapUtils.isNotEmpty(map)){
                data.put("store", map.get("id"));
                data.put("rcsArea", map.get("rcsArea"));
                data.put("cityName", map.get("cityName"));
                data.put("detailArea", map.get("detailArea"));
            }
            data.put("project_name", project_name);
            data.put("subjectName", subjectName);
            data.put("QC_task_name", QC_task_name);
            data.put("objectNumber", taskCode);
            data.put("subjectPerson", subjectPerson);
            data.put("persons", persons);
            data.put("objectName", leJuanDataDTO.getTaskName());
            data.put("state", leJuanDataDTO.getQcStatus());
            data.put("timeConsuming", leJuanDataDTO.getDiffTime());
            data.put("SubmitTime", leJuanDataDTO.getSubmitTime()==null?null:leJuanDataDTO.getSubmitTime().replaceAll("/","-"));
            data.put("EndTime", leJuanDataDTO.getEndTime());
            data.put("QcTime", leJuanDataDTO.getQcTime()==null?null:leJuanDataDTO.getQcTime().replaceAll("/","-"));
            data.put("DiffQcTime", leJuanDataDTO.getDiffQcTime());
            data.put("QcRemark", leJuanDataDTO.getQcRemark());
            data.put("QcName", leJuanDataDTO.getQcName());
            data.put("djxq", id);
            String bizId = this.getBizObjectFacade().saveBizObject(userId, bizObjectModel, false);
        }
    }


    /**
     * @Description :每天晚上23:30 乐卷同步：定时器
     * @param ：
     * @author : Liun
     * @date : 2021/3/16
     */
    @Scheduled(cron = "0 30 23 ? * *")
    public void createTimingTask(){
        this.getDataPubblic();
    }

    /**
     * @Description : 修改自建任务完成比例
     * @param ：
     * @author : Liun
     * @date : 2021/3/17
     */
    @Scheduled(cron = "0 50 23 ? * *")
    public void updateSelfEndProportion(){
        String tableName="iden7_self_task_send";
        getLeJuanDataService.updateEndProportion(tableName);
    }

    /**
     * @Description :修改项目任务新增完成比例
     * @param ：
     * @author : Liun
     * @date : 2021/3/17
     */
    @Scheduled(cron = "0 55 23 ? * *")
    public void updateVisitAndAuditEndProbability(){
        getLeJuanDataService.updateVisitAndAuditEndProbability();
    }

    /**
     * @Description : 项目任务每天早上八点消息通知未审核，待跟进数据
     * @param ：
     * @author : Liun
     * @date : 2021/3/23
     */
    @Scheduled(cron = "0 30 9 ? * *")
    public void sendMessageToQCProjectTask(){
        getLeJuanDataService.sendMessageToQCProjectTask();
    }

    /**
     * @Description :自办任务
     * @param ： null
     * @author : Liun
     * @date : 2021/3/24
     */
    @Scheduled(cron = "0 40 9 ? * *")
    public void sendMessageToQCTask(){
        getLeJuanDataService.sendMessageToQCTask();
    }
}
